<?php

namespace App\Http\Controllers\Vote;

use App\Entities\VoteCandidate;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class ApiController
{
    protected $stopWords = [
        '的',
        '地',
        '得',
        '啊',
        '阿',
        '哎',
    ];

    public function searchCandidate(Request $request, $activityId)
    {
        $keyword = $request->query->get('q');

        if ("" === $keyword || $keyword === null) {
            return response()->failed('关键词不能为空');
        }

        if (in_array($keyword, $this->stopWords, false)) {
            return response()->failed('请勿使用停止词进行搜索');
        }

        $cache = app('cache');
        $key = 'search:vote:'. md5($activityId.$keyword);

        $ids = $cache->remember($key, 5, function () use ($activityId, $keyword) {
            return VoteCandidate::query()
                ->where('activity_id', $activityId)
                ->where(function ($query) use ($keyword) {
                    $query->where('title', 'LIKE', '%'.$keyword.'%');
                    if (is_numeric($keyword)) {
                        $query->orWhere('code', $keyword + 0);
                    }
                })
                ->orderBy('weight', 'DESC')
                ->orderBy('code', 'ASC')
                ->pluck('id');
        });

        return response()->success(compact('ids'));
    }
}
